<?php
    /*\
     *  Htaccess - oh.framework
     *  -----------------------
     *  name: htaccess
     *  sign: 
     *  description: manage htaccess file of script called
    \*/
   	
	// Interface function	
	function oh_module_htaccess($tokens) {
		global $oh_object_htaccess;
		return $oh_object_htaccess;	
	} 
	
	// Main class of module
	class oh_class_htaccess {		
		function oh_class_htaccess() {
		}
		function status() {
			if (file_exists(oh("path.script")."/.htaccess")) {
				return "enabled";				
			} else {
				return "disabled";								
			}
		}
		function disable() {
			copy(oh("path.script")."/.htaccess",oh("path.script")."/.htaccess.disabled");
			unlink(oh("path.script")."/.htaccess");
		}
		function enable() {
			if (!file_exists(oh("path.script")."/.htaccess")) {
			 	$this->write_htaccess();
			} else {
				if (file_exists(oh("path.script")."/.htaccess.disabled")) {
					copy(oh("path.script")."/.htaccess.disabled",oh("path.script")."/.htaccess");
					unlink(oh("path.script")."/.htaccess.disabled");				
				}
			}
		}
		function insert($handle,$code) {
			$handle = oh_name_sanitize($handle);
			$ht = file_get_contents(oh("path.script")."/.htaccess");			
			if (strpos($ht,"##oh:htaccess::$handle") === FALSE) {
				$ht .= 	"\n\n"
					.	"##oh:htaccess::$handle\n"
					.	$code."\n"
					.	"##oh:htaccess:.$handle\n";
				file_put_contents(oh("path.script")."/.htaccess",$ht);
			}
		}
		function remove($handle) {
			$handle = oh_name_sanitize($handle);
			$ht = file_get_contents(oh("path.script")."/.htaccess");			
			if (strpos($ht,"##oh:htaccess::$handle") !== FALSE) {
				$s0 = strpos($ht,"##oh:htaccess::$handle");
				$s1 = strpos($ht,"##oh:htaccess:.$handle")+strlen("##oh:htaccess:.$handle");
				$ht = substr($ht,0,$s0).substr($ht,$s1);
				file_put_contents(oh("path.script")."/.htaccess","\n".trim($ht));
			}
		}
		function get() {
			return file_get_contents(oh("path.script")."/.htaccess");
		}
		function write_htaccess() {		
			$p = oh_get_file_permission(oh("path.script"));
			if ($p == "0777") {
				$base = dirname($_SERVER["SCRIPT_NAME"])."/";
		        $script = $_SERVER["SCRIPT_NAME"];
				file_put_contents(
					oh("path.script")."/.htaccess",
					"\n".
					"##oh:htaccess::default					\n".
					"RewriteEngine On						\n".
					"RewriteBase $base						\n".
					"RewriteCond %{REQUEST_FILENAME} !-f	\n".
					"RewriteCond %{REQUEST_FILENAME} !-d	\n".
					"RewriteRule . $script [L]				\n".
					"##oh:htaccess:.default					\n"
				);
			} else {
				oh_message("Set permission to 777 on ".oh("path.script"));
			}
		}
	}
		
	// Main object of module
	global $oh_object_htaccess;
	$oh_object_htaccess = new oh_class_htaccess();
?>
